#include "rttIODevice.h"

#include <unistd.h>
#include <poll.h>
#include <fcntl.h>

using namespace NXMFC;

rttIODevice::rttIODevice() : fd(-1)
{

}

rttIODevice::~rttIODevice()
{

}

bool rttIODevice::open(const char *name, bool nonblock)
{
    int of = O_RDWR;

    if (nonblock)
        of |= O_NONBLOCK;

    fd = ::open(name, of);
    if (fd < 0)
        return false;

    return true;
}

void rttIODevice::close()
{
    if (fd >= 0)
        ::close(fd);
}

bool rttIODevice::waitForReadyRead(int ms)
{
    struct pollfd pf;

    pf.fd = fd;
    pf.events = POLLIN;

    if (::poll(&pf, 1, ms) <= 0)
        return false;

    if (pf.revents & POLLIN)
        return true;

    return false;
}

int rttIODevice::read(void *buf, unsigned max)
{
    return ::read(fd, buf, max);
}

int rttIODevice::readAll(void *buf, unsigned max, int timeout_ms)
{
    int len = 0;
    uint8_t *p = (uint8_t *)buf;

    while (max)
    {
        int ret;

        if (!waitForReadyRead(timeout_ms))
            break;

        ret = read(p, max);
        if (ret <= 0)
            break;

        p += ret;
        max -= ret;
        len += ret;
    }

    return len;
}

int rttIODevice::ioctl(int cmd, void *arg)
{
    return ::ioctl(fd, cmd, arg);
}

int rttIODevice::write(const void *buf, unsigned max)
{
    return ::write(fd, buf, max);
}
